<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row v-show="showSearch">
				<el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
					<el-row>
						<el-form-item label="证书名称" prop="certificateName">
							<el-select filterable v-model="state.queryForm.certificateTemplateName" placeholder="请选择证书名称" clearable>
								<el-option :label="item.certificateTemplateName" :value="item.certificateTemplateName"
									v-for="(item, index) in certificate_name"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="证书类型" prop="certificateType">
							<el-select clearable @change="typeChange" filterable v-model="state.queryForm.certificateType"
								placeholder="请选择证书类型">
								<el-option :label="item.label" :value="item.value" v-for="(item, index) in certificate_type"
									:key="index"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="证书性质" prop="certificateNature">
							<el-select clearable @change="natureChange" filterable v-model="state.queryForm.certificateNature"
								placeholder="请选择证书性质">
								<el-option :label="item.label" :value="item.value" v-for="(item, index) in certificate_nature"
									:key="index"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="颁发机构" prop="authority">
							<el-select clearable @change="authChange" filterable v-model="state.queryForm.authority"
								placeholder="请选择颁发机构">
								<el-option :label="item.label" :value="item.value" v-for="(item, index) in certification_authority"
									:key="index"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item>
							<el-button icon="search" type="primary" @click="getDataList"> 查询 </el-button>
							<el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()"
								v-auth="'train_zsglCertificateTemplate_add'">
								新 增
							</el-button>
							<el-button plain :disabled="multiple" icon="Delete" type="danger"
								v-auth="'train_zsglCertificateTemplate_del'" @click="handleDelete(selectObjs)">
								删除
							</el-button>
							<el-button type="danger" @click="ontemplateDownload">证书模版下载</el-button>
							<el-button icon="Refresh" @click="resetQuery">重置</el-button>
						</el-form-item>
					</el-row>
				</el-form>
			</el-row>
			<!--			<el-row>-->
			<!--				<div class="mb8" style="width: 100%">-->
			<!--					<right-toolbar-->
			<!--						v-model:showSearch="showSearch"-->
			<!--						:export="'train_zsglCertificateTemplate_export'"-->
			<!--						@exportExcel="exportExcel"-->
			<!--						class="ml10 mr20"-->
			<!--						style="float: right"-->
			<!--						@queryTable="getDataList"-->
			<!--					></right-toolbar>-->
			<!--				</div>-->
			<!--			</el-row>-->
			<el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle"
				@sort-change="sortChangeHandle">
				<el-table-column type="selection" width="40" align="center" />
				<el-table-column type="index" label="序号" width="80" />
				<!--          <el-table-column prop="certificateId" label="证书业务id"  show-overflow-tooltip/>-->
				<el-table-column prop="certificateTemplateName" label="证书名称" show-overflow-tooltip />
				<el-table-column prop="certificateTemplateId" label="证书模板编码" show-overflow-tooltip></el-table-column>
				<el-table-column prop="certificateType" label="证书类型" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag @click="censhi1(scope.row)" :options="certificate_type"
							:value="scope.row.certificateType"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column prop="certificateNature" label="证书性质" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="certificate_nature" :value="scope.row.certificateNature"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column prop="authority" label="颁发机构" show-overflow-tooltip>
					<template #default="scope">
						<dict-tag :options="certification_authority" :value="scope.row.authority"></dict-tag>
					</template>
				</el-table-column>
				<el-table-column width="60" label="logo" show-overflow-tooltip align="center">
					<template #default="scope">
						<el-image :src="actionUrl + '/downloadFile/' + scope.row.photoUid">
							<template #error>
								<div>未上传logo</div>
							</template>
						</el-image>
						<!--            <el-image :src="require(`${actionUrl}/downloadFile/${scope.row.photoUid}`)"></el-image>-->
					</template>
				</el-table-column>
				<el-table-column prop="isPermanent" label="有效期" show-overflow-tooltip ref="table-1">
					<template #default="scope">
						<el-tag @click="ceshi1(scope.row)" type="primary">{{ scope.row.isPermanent === 1 ? '永久' : scope.row.timeValid
							== 0 ? `${scope.row.effectiveYear}年` : `${scope.row.startTime}--${scope.row.endTime}` }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150">
					<template #default="scope">
						<el-button icon="Search" text type="primary" v-auth="'train_zsglCertificateTemplate_del'"
							@click="openPreview(scope.row)">
							预览
						</el-button>
						<el-button icon="edit-pen" text type="primary" v-auth="'train_zsglCertificateTemplate_edit'"
							@click="formDialogRef.openDialog(scope.row.id)">编辑</el-button>
						<el-button icon="delete" text type="primary" v-auth="'train_zsglCertificateTemplate_del'"
							@click="handleDelete([scope.row.id])">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" @refreshName="getName" />
		<!--预览-->
		<el-dialog v-model="dialogTableVisible" width="1000" style="text-align: center">
			<el-image v-loading="loading" style="width: 800px; height: 600px" :src="mapSrc" placeholder="加载中。。。" :fit="fit" />
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemZsglCertificateTemplate">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs, getcertificateName, getCertificatePreview, getCertificatePreview2 } from '/@/api/train/zsglCertificateTemplate';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useDict } from '/@/hooks/dict';
import { office, officeView } from "/@/api/train/kszlFile";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典
const { certification_authority, certificate_nature, yes_no_type, certificate_type } = useDict(
	'certification_authority',
	'certificate_nature',
	'yes_no_type',
	'certificate_type'
);
// 定义变量内容
const formDialogRef = ref();
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
});

const ceshi1 = (e: any) => {
	console.log(e)
}
const censhi1 = (e: any) => {
	console.log(e)
}

// 证书名称
const certificate_name = ref([]);

// 预览对话框
const dialogTableVisible = ref(false)


// 记载组件开启
const loading = ref(true)
// 获取证书名称
onMounted(() => {
	getName();
	office().then((res) => {
		actionUrl.value = res.data;
	});
	officeView().then(res => {
		actionUrl1.value = res.data
	})
});

// 后台请求路径
const actionUrl = ref();
// 文件预览路径
const actionUrl1 = ref()
// 文件预览地址
// const allurl = ref()
const mapSrc = ref()
// 预览证书模版
// const handlepreivew = (e:any) => {
//   console.log(e.fileUid)
//   let originalUrl = `${actionUrl.value}/downloadFilec?id=${e.fileUid}`;
//   let previewUrl  = originalUrl +  `&fullfilename=${e.fileUid}.${e.fileName}`
//   //转换为 Base64 编码
//   let base64EncodedUrl = btoa(previewUrl);
//   //使用 encodeURIComponent 编码
//   let encodedUrl = encodeURIComponent(base64EncodedUrl);
//   allurl.value = actionUrl1.value + encodedUrl
//   window.open(allurl.value)
// }

// 证书模板预览标准模板
const openPreview = async (row: any) => {
	mapSrc.value = ''
	dialogTableVisible.value = true
	const res = await getCertificatePreview2(row.fileUid)
	const btoa1 = btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
	mapSrc.value = `data:image/png;base64,${btoa1}`
	loading.value = false
}

// 下载证书模版
const ontemplateDownload = () => {
	try {
		// 服务器地址拼接 + 文件下载接口
		let baseURL = import.meta.env.VITE_API_URL;
		window.open(baseURL + "/train/zsglCertificateTemplate/localFile/证书模板.pptx")
	} catch (error) {
		console.error('下载文件时出错', error)
	}
}
// 获取证书名称
const getName = async () => {
	const res = await getcertificateName();
	console.log(res);
	certificate_name.value = res;
};

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, downBlobFile, tableStyle } = useTable(state);
console.log(state.dataList);
// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	state.queryForm.certificateTemplateName = null
	// 清空多选
	selectObjs.value = [];
	// getDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/train/zsglCertificateTemplate/export', Object.assign(state.queryForm, { ids: selectObjs }), 'zsglCertificateTemplate.xlsx');
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm('此操作将永久删除');

	} catch {
		return;
	}

	try {
		const res = await delObjs(ids);
		console.log(res)
		getDataList();
		useMessage().success(res.data.msg);
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
</script>
